
package database;

import java.awt.Color;
import java.sql.DriverManager;
import main.GlobalMethods;

/**
 *
 * @author Raed Shomali
 */
public class COINCOMODatabaseManager 
{
    public static String HOST = "localhost" ;
    public static String PORT = "5432" ;
    public static String DB_NAME = "COINCOMO" ;
    public static String DB_DRIVER = "org.postgresql.Driver" ;
    public static String DB_TYPE = "postgresql" ;
    public static String USERNAME = "postgres" ;
    public static String PASSWORD = "test" ;
    
    // Default Database Constants
    public static final String POSTGRES_TYPE = "postgresql" ;
    public static final String POSTGRES_DRIVER = "org.postgresql.Driver" ;
    public static final String POSTGRES_PORT = "5432" ;
    
    public static final String MYSQL_TYPE = "mysql" ;
    public static final String MYSQL_DRIVER = "com.mysql.jdbc.Driver" ;
    public static final String MYSQL_PORT = "3306" ;
    
    /**
     * 
     * @return boolean that determines the success or failure of registeration
     */
    public static boolean registerDriver()
    {
        // Keep Track Of Driver Being Registered
        boolean isSuccessful = false ;
        
        try
        {
            String DB_URL = "jdbc:" + DB_TYPE + "://" + HOST + ":" + PORT + "/" + DB_NAME ;
            
            new DBConnectionDriver( DB_DRIVER , DB_URL , USERNAME ,PASSWORD );
            
            // Driver Registered Successfully
            isSuccessful = true ;
        }
        catch ( Exception e )
        {
            // Driver Failed To be Registered
        }
        
        return isSuccessful ;
    }

    /**
     * 
     * @return a DB Connection
     */
    public static DBConnection getConnection()
    {
        try
        {
            // Connection Object
            DBConnection connection = (DBConnection) DriverManager.getConnection( "jdbc:jdc:jdcpool" );
       
            // For Better Performance (Batch Commiting)
            connection.setAutoCommit( false ) ;
            
            return connection;
        }
        catch( Exception e )
        {
            // Sorry, We were unable to Connect to the Database.
            GlobalMethods.updateStatusBar( "Unable to connect to Database." , Color.RED );
            
            return null;
        }
    }

    /**
     * 
     * @param connection to be disconnected
     */
    public static void disconnect( DBConnection connection )
    {
        // Make Sure Passed Connection Exists.
        if( connection != null )
        {
            try
            {        
                // Save
                connection.commit() ;
   
                // Free Resources
                connection.close();
            }
            catch( Exception e )
            {
                GlobalMethods.updateStatusBar( "Could Not Disconnect Database: " + e.getMessage() , Color.RED );
            }
        }
    }
}
